import json

from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
import base64
import pickle


class CartsView(View):
    def post(self, request):
        # 1 接收数据
        json_data = json.loads(request.body)
        sku_id = json_data.get("sku_id")
        count = json_data.get("count")
        # 2 验证数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "商品不存在"})
        try:
            count = int(count)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "数量错误"})
        # 3 判断用户是否登录 没有登录就是AnonymouseUser对象
        user = request.user
        if user.is_authenticated:
            # 4 如果用户登录 保存到redis
            # 4.1 连接redis
            redis_conn = get_redis_connection("carts")
            pl = redis_conn.pipeline()
            # 4.2 操作hash
            pl.hincrby("cart_%s" % user.id, sku_id, count)
            # 4.3 操作set
            pl.sadd("selected_%s" % user.id, sku_id)
            pl.execute()
            # 4.4 返回响应
            return JsonResponse({"code": 0, "errmsg": "ok"})
        else:

            # 5 如果用户未登录 保存到cookie
            # 获取cookie数据
            cart_cookie = request.COOKIES.get("cart")
            # 保存 字典-bytes-base64-字符串
            # 获取 字符串-base64decode-loads-字典
            if cart_cookie:
                carts = pickle.loads(base64.b64decode(cart_cookie))
            else:
                carts = {}
            # 5.1 生成字典数据
            if sku_id in carts:
                # 购物车已经有sku_id对应的商品了 做数量的累加
                # 取出原来的数量
                count_ori = carts[sku_id]["count"]
                count += count_ori
            # 把数据添加到字典
            carts[sku_id] = {
                "count": count,
                "selected": True
            }
            # 5.2 字典转为bytes
            carts_bytes = pickle.dumps(carts)
            # 5.3 bytes转base64 转完后b64carts也是bytes类型
            b64carts = base64.b64encode(carts_bytes)
            # 5.4 添加cookie
            response = JsonResponse({"code": 0, "errmsg": "ok"})
            # b64carts.decode()把二进制转为字符串保存
            response.set_cookie("cart", b64carts.decode(), max_age=3600 * 24 * 10)
            # 6 返回响应
            return response

    def get(self, request):
        # 1 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 2 登录用户去redis查询
            # 2.1 连接redis
            redis_conn = get_redis_connection("carts")
            # 2.2 hash
            skuid_count = redis_conn.hgetall("cart_%s" % user.id)
            # 2.3 set
            selected_skuids = redis_conn.smembers("selected_%s" % user.id)
            carts = {}
            # 2.4 把查询的数据 构造成和cookie里数据一样的格式
            for sku_id, count in skuid_count.items():
                carts[int(sku_id)] = {
                    "count": int(count),
                    "selected": sku_id in selected_skuids
                }
        else:
            # 3 未登录用户去cookie查询
            # 3.1 读取cookie数据
            cart_cookie = request.COOKIES.get("cart")
            # 保存 字典-bytes-base64-字符串
            # 获取 字符串-base64decode-loads-字典
            if cart_cookie:
                carts = pickle.loads(base64.b64decode(cart_cookie))
            else:
                carts = {}
        # 4 根据商品id查商品信息
        # 遍历所有的商品id
        sku_ids = carts.keys()
        # 查询所有的商品
        skus = SKU.objects.filter(id__in=sku_ids)
        # 5 把数据转为字典
        sku_list = []
        for sku in skus:
            sku_list.append({
                "id": sku.id,
                "name": sku.name,
                "price": sku.price,
                "default_image_url": sku.default_image.url,
                "count": carts[sku.id]["count"],
                "selected": carts[sku.id]["selected"]
            })
        # 6 返回响应
        return JsonResponse({"code": 0, "errmsg": "ok", "cart_skus": sku_list})

    def put(self, request):
        """修改购物车数据"""
        # 1 获取用户user
        user = request.user
        # 2 接收数据 修改后的sku_id sku_count seleted
        json_data = json.loads(request.body)
        sku_id = json_data.get("sku_id")
        count = json_data.get("count")
        selected = json_data.get("selected")
        # 3 验证数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseBadRequest("商品sku_id不存在")
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return HttpResponseBadRequest("参数count有误")
        if user.is_authenticated:
            # 4 登录后 修改redis
            # 连接redis
            redis_conn = get_redis_connection("carts")
            # hash
            redis_conn.hset("cart_%s" % user.id, sku_id, count)
            # set 无序无重复的集合
            if selected:
                redis_conn.sadd("selected_%s" % user.id, sku_id)
            else:
                redis_conn.srem("selected_%s" % user.id, sku_id)
            cart_sku = {"count": count, "selected": selected, "sku_id": sku_id}
            # 返回响应
            return JsonResponse({"code": 0, "errmsg": "ok", "cart_sku": cart_sku})
        else:
            # 4 未登录
            # 修改cookie
            # 获取cookie数据
            cart_cookie = request.COOKIES.get("cart")
            # 数据解码
            carts = pickle.loads(base64.b64decode(cart_cookie))
            # 更新数据
            carts[sku_id]["count"] = count
            carts[sku_id]["selected"] = selected
            # print(selected)
            # 编码
            # 字典转bytes
            carts_bytes = pickle.dumps(carts)
            # bytes转base64
            b64carts = base64.b64encode(carts_bytes)
            # 返回响应
            cart_sku = {"count": count, "selected": selected, "sku_id": sku.id}
            # 添加cookie
            response = JsonResponse({"code": 0, "errmsg": "ok", "cart_sku": cart_sku})
            # b64carts.decode()把二进制转为字符串 保存
            response.set_cookie("cart", b64carts.decode(), max_age=3600 * 24 * 10)
            return response

    def delete(self, request):
        # 1 获取用户user
        user = request.user
        # 2 接收数据
        json_data = json.loads(request.body)
        sku_id = json_data.get("sku_id")
        # 验证数据
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseBadRequest("商品不存在")
        if user.is_authenticated:
            # 4 登录后redis中删除
            redis_conn = get_redis_connection("carts")
            # hash
            redis_conn.hdel("cart_%s" % user.id, sku_id)
            # set
            redis_conn.srem("selected_%s" % user.id, sku_id)
            # 返回响应
            return JsonResponse({"code": 0, "errmsg": "ok"})
        else:
            # 5 未登录
            # cookie 中删除
            cart_cookie = request.COOKIES.get("cart")
            # 数据解码
            carts = pickle.loads(base64.b64decode(cart_cookie))
            # 更新数据
            del carts[sku_id]
            # 字典转bytes
            carts_bytes = pickle.dumps(carts)
            # bytes 转base64
            b64carts = base64.b64encode(carts_bytes)
            response = JsonResponse({"code": 0, "errmsg": "ok"})
            response.set_cookie("cart", b64carts.decode(), max_age=3600 * 24 * 10)
            # 返回响应
            return response


class CartsSelectAllView(View):
    """全选购物车"""

    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseBadRequest('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录 修改redis
            redis_conn = get_redis_connection("carts")
            cart = redis_conn.hgetall("cart_%s" % user.id)
            sku_id_list = cart.keys()
            if not sku_id_list:
                return JsonResponse({"code": 0, "errmsg": "ok"})
            if selected:
                # 全选
                redis_conn.sadd("selected_%s" % user.id, *sku_id_list)
            else:
                # 取消全选
                redis_conn.srem('selected_%s' % user.id, *sku_id_list)
            return JsonResponse({"code": 0, "errmsg": "ok"})
        else:
            # 用户未登录 修改cookie
            cart_cookie = request.COOKIES.get("cart")
            # 数据解码
            carts = pickle.loads(base64.b64decode(cart_cookie))
            for sku_id in carts:
                carts[sku_id]["selected"] = selected
            cookie_cart = base64.b64encode(pickle.dumps(carts)).decode()
            response = JsonResponse({"code": 0, "errmsg": "ok"})
            response.set_cookie("cart", cookie_cart, max_age=3600 * 24 * 10)
            return response


class CartsSimpleView(View):
    def get(self, request):
        user = request.user
        if user.is_authenticated:
            # 用户已经登录 查询redis
            redis_conn = get_redis_connection("carts")
            redis_cart = redis_conn.hgetall("cart_%s" % user.id)
            cart_selected = redis_conn.smembers("selected_%s" % user.id)
            # 将redis中的两个数据统一格式 跟cookie中的格式一致 方便统一查询
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    "count": int(count),
                    "selected": sku_id in cart_selected
                }
        else:
            # 用户未登录 查询cookie
            cart_str = request.COOKIES.get("cart")
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str))
            else:
                cart_dict = {}
        # 构造简单购物车JSON数据
        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                "id": sku.id,
                "name": sku.name,
                "count": cart_dict.get(sku.id).get("count"),
                "default_image_url": sku.default_image.url
            })
        # 返回响应
        return JsonResponse({"code": 0, "errmsg": "ok", "cart_skus": cart_skus})
